<?php
/**
 * 美食TAG管理 - 编辑TAG - 提交程序
 *
 * @copyright dongping
 * @since 2012-03-24
 */


include_once($_SERVER["DOCUMENT_ROOT"] . "/core/inc.php");
include_once($_SERVER["DOCUMENT_ROOT"] . "/core/admin.inc.php");
include_once($_SERVER["DOCUMENT_ROOT"] . "/include/foodv2/inc.php");

$g_cgival = array();
$g_pro = array();
$g_show = array();



function check_cgi_pro()
{
	global $g_cgival, $g_pro, $g_show;
	
	//check refer  -  add by xinwei
	if(! security_check::check_refer())
	{
		throw new Exception("来路不明");
	}
	
	cgi::both($g_cgival["turn_in"], "turn_in", 0);
	if ($g_cgival["turn_in"] != 1)
	{
		$g_cgival["turn_in"] = 0;
	}
	
	
	// 搜索词
	cgi::both($g_cgival["tag"], "tag", "");
	$g_cgival["tag"] = string::un_script_code($g_cgival["tag"]);
	$g_cgival["tag"] = string::un_html($g_cgival["tag"]);
	if (strlen(iconv("utf-8", "gbk", $g_cgival["tag"])) > 14)
	{
		throw new Exception("抱歉，TAG最多7个汉字，14个字符！");
	}
	
	
	// 分类
	if (is_array($_POST["tag_class"]))
	{
		foreach($_POST["tag_class"] as $k => $class)
		{
			$class = string::un_script_code($class);
			$class = string::un_html($class);
			
			$g_cgival["tag_class"][$class] = $class;
		}
	}
	
	
}


function get_data()
{
	global $g_cgival, $g_pro, $g_show, $config;
	
	$g_show = $g_cgival;
	
	
	$tag_class = $g_cgival["tag_class"];
	$tag = $g_cgival["tag"];
	
	// 拿到当前站点的site_id
	$site_id = admin::admin_get_user_site_id();	// 拿到当前站点的site_id
	$admin_id = admin::admin_get_login_uid();	// 拿到当前管理员ID
	$admin_name = admin::admin_get_login_user_name();	// 拿到当前管理员用户名

	
	$admin_log = new admin_log();
	$db = new db_food_tag();
// 	$db->debug = true;
	
	
	// 把当前TAG的所有分类信息查出来
	$data = $db->admin_get_list_by_tags_ary($site_id, array($tag));
	if (is_array($data))
	{
		$del_tag_class = array();					// 存储需要删除的TAG分类
		foreach($data as $k =>$v)
		{
			$class = $v["tag_class"];
			if (array_key_exists($class, $tag_class))
			{
				unset($tag_class[$class]);
			}
			else
			{
				$del_tag_class[$class] = $class;
			}
		}
		
		foreach($del_tag_class as $k => $class)
		{
			$db->admin_delete_data($site_id, $tag, $class, $admin_id, $admin_name);
		}
	}
	
	
	// 写入数据库中没有的tag -> tag_class
	if (is_array($tag_class))
	{
		foreach($tag_class as $k=>$class)
		{
			$db->admin_insert_data($site_id, $class, $tag, 0, 0, 0, $admin_id, $admin_name);
		}
	} 
	
	$tag_class_str = implode(',', $tag_class);
	$admin_log->admin_insert_log_info($admin_id, $site_id, 1, "添加/编辑 标题为：{$tag} 的美食tag分类");
}




try
{
	admin_check_login();
	// 	admin_check_user_priv("foodv2/main_nav.php");

	check_cgi_pro();
	get_data();
}
catch(Exception $e)
{
	$g_show["error"] = 1;
	$g_show["errmsg"] = $e->getMessage();
}

show_pro();
exit;


function show_pro()
{
	global $g_cgival, $g_pro, $g_show;

	if (isset($_GET["debug"]))
	{
		echo "<pre>";
		print_r($g_show);
	}

	echo json_encode($g_show);
}